import { UserManager } from "oidc-client-ts"

const cognitoAuthConfig = {
    authority: config.authority,
    client_id: config.clientId,
    redirect_uri: config.redirect_uri, // 你的重定向 URI，这里使用的是本地开发环境
    response_type: config.response_type,
    scope: config.scope,
}

// 创建 UserManager 实例
export const userManager = new UserManager(cognitoAuthConfig)

// 登录重定向
export async function signInRedirect() {
    await userManager.signinRedirect()
}

// 登出重定向
export async function signOutRedirect() {
    // const clientId = "1j2cssp4v59f8818p1dh3d5n5j";
    // const logoutUri = "http://localhost:5173";  // 登出后的重定向页面
    // const cognitoDomain = "https://us-east-1x86f27lzt.auth.us-east-1.amazoncognito.com";

    const clientId = config.clientId
    const logoutUri = config.logoutUri // 登出后的重定向页面
    const cognitoDomain = config.cognitoDomain

    window.location.href = `${cognitoDomain}/logout?client_id=${clientId}&logout_uri=${encodeURIComponent(logoutUri)}`
}

// 处理登录回调并获取用户信息
export function handleSigninCallback() {
    return userManager.signinCallback().then(function(user) {
        return user
    })
}